<template>
    <div id="CommitmentCard" class="w-h-100 pos-r flex-1 apply-container page-public-s" style="box-sizing: border-box;overflow:hidden;">
        <div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px;">
            <div v-if="$hasPer('commitment:add') || $hasPer('commitment:excel')" style="box-sizing: border-box;">
                <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" ref="queryForm" :inline="true">
                        <el-form-item>
                            <el-button v-if="$hasPer('commitment:add')" @click="nodeClick('')" icon="ele-Plus" type="primary"> 新增 </el-button>
                            <el-button v-if="$hasPer('commitment:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <div style="box-sizing: border-box;" class="flex-1 pos-r">
                <div class="pos-a w-h-100" style="box-sizing: border-box;">
                    <el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px;">
                        <div style="" class="w-h-100 ver-flex">
                            <div class="flex-1 pos-r">
                                <div class="pos-a w-h-100">
                                    <el-table 
                                        ref="excelRef"
                                        :data="list" 
                                        class="w-h-100" 
                                        style="width: 100%" 
                                        border 
                                        v-loading="loading" 
                                        element-loading-background="rgba(0, 0, 0, 0.5)"
                                    >

                                        <el-table-column width="430" :show-overflow-tooltip="true" label="公告时间"  align="center" prop="d_PublicDate" sortable>
                                            <el-table-column :show-overflow-tooltip="true" width="430" align="center">
                                                <template #header>
                                                    <SearchModel typeId="d_Public" typeVal="datetimerange" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.d_PublicDate">{{ scope.row.d_PublicDate }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="240" :show-overflow-tooltip="true" label="主要负责人"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="240" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Principal" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_Principal">{{ scope.row.v_Principal }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="240" :show-overflow-tooltip="true" label="描述"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="240" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Content" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_Content">{{ scope.row.v_Content }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column width="430" :show-overflow-tooltip="true" label="传输(到显示屏)时间" align="center" prop="d_TransferTime" sortable>
                                            <el-table-column :show-overflow-tooltip="true" width="430" align="center">
                                                <template #header>
                                                    <SearchModel typeId="d_Transfer" typeVal="datetimerange" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.d_TransferTime">{{ scope.row.d_TransferTime }}</span>
                                                    <span v-else>-</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="传输(到显示屏)操作人"  align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_TransferOperatorName">{{ scope.row.v_TransferOperatorName }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="createdTime" label="创建时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.createdTime">{{ scope.row.createdTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column width="300" label="操作" align="center" fixed="right">
                                            <el-table-column :show-overflow-tooltip="true" width="300" align="center">
                                                <template #header>
                                                    <el-button class="icon-e" @click='searchClick' icon="ele-Search" size="small" type="primary" text> 查询 </el-button>
                                                    <el-button class="icon-e clear-bg" style="background-color: transparent !important;" size="small" @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                                </template>
                                                <template #default="scope">
                                                    <template v-if="$hasPer('commitment1:edit') || $hasPer('commitment2:delete') || $hasPer('commitment:sync')">
                                                        <el-button v-if="$hasPer('commitment:sync')" @click="syncHandel(scope.row)" class="icon-e" icon="ele-Wallet" size="small" text type="success">同步至大屏</el-button>
                                                        <el-button v-if="$hasPer('commitment1:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary">编辑</el-button>
                                                        <el-button v-if="$hasPer('commitment2:delete')" @click="deleteHandle(scope.row.id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger">删除</el-button>
                                                    </template>
                                                    <template v-else>
                                                        <el-button class="icon-e" size="small" text type="danger">暂无操作权限</el-button>
                                                    </template>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <!-- 新增/编辑 -->
        <AddEditCommitmentCard
            :repairInfo="repairInfo"
            :isUseDialog="isUseDialog"
            @updateData="getData"
            @cancelUseClick="cancelUseClick"
            @controlUseClick="controlUseClick"
        />
        <!-- 详情 -->
        <DetailModel
            :detailInfo="detailInfo"
            :MdetailDialog="MdetailDialog"
            labelWidth="140px"
            @cancelDetailClick="cancelDetailClick"
        />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted , reactive , toRaw , toRefs } from 'vue';
import getTableData from '/@/utils/getTableData';
import AddEditCommitmentCard from '../component/sms/add-edit-CommitmentCard.vue';
import SearchModel from '../component/search-model.vue';
import DetailModel from '../component/detail-model.vue';
import { confirmFun } from '../component/messageTs';
import { exportToExcel } from '/@/utils/exportToExcel';

import {
    SMSDCRiskJudPubPage,
    SMSDCRiskPartitionList,
    SMSDCHazopDetail,
    SMSDCRiskJudPubDelete,
    SMSDCRiskJudPubBathaAddOrUpdate,
} from '/@/api/centerControl/sms';
import { sysFileInfoPage } from '/@/api/centerControl/pubilc';
import { ElMessageBox , ElMessage } from 'element-plus';

export default defineComponent( {
    name: 'CommitmentCard',
    components: { AddEditCommitmentCard , SearchModel , DetailModel },
    setup(props){
        const isUseDialog = ref(false); // 新增/编辑弹出框隐藏/显示
        const repairInfo = ref(); // 传递子组件数据

        /*** 新增/编辑 */
        const nodeClick = (val: any) => {
            repairInfo.value = val === '' ? '' : JSON.stringify(val);
            isUseDialog.value = true;
        }

        /*** HAZOP取消事件 */
        const cancelUseClick = () => {
            isUseDialog.value = false;
        }

        /*** HAZOP提交事件 */
        const controlUseClick = () => {
            isUseDialog.value = false;
        }

        /*** HAZOP删除事件 */
        const deleteHandle = (val: number, updateFun: Function) => {
            ElMessageBox.confirm('请确定删除此条数据？','提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                let param = {id : val};
                try {
                    let res:any = await SMSDCRiskJudPubDelete(param);
                    if(res.success){
                        updateFun()
                    }
                } catch (err) { return }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        }

        /*** 同步至大屏 */
        const syncHandel = (row: any) => {
            let param: any = {};
            confirmFun('是同步至大屏？','提示','warning','取消').then(async(isConfirmed: any) => {
                if(isConfirmed){
                    param.id = row.id;
                    try{
                        let res: any = await SMSDCRiskJudPubBathaAddOrUpdate(param);
                        console.log(res,'res12')
                    }catch(err: any){
                        console.log('错误信息', err)
                    }
                }
            });
            console.log(row,'row')
        }

        /*** ================================= 详情类数据操作 =================================  */
        const MdetailDialog = ref(false);
        const detailInfo = ref();

        // 获取文件
        const getFileFun = async (sourceId: number) => {
            let param: any = {};
            param.PageNo = 1;
            param.PageSize = 99999;
            param.sourceId = sourceId;
            let res: any = await sysFileInfoPage(param);
            if(res.success) return res.data.rows;
        }
        /*** 获取详情接口数据 */
        const getDetailFun = async (id: number) => {
            let res: any = await SMSDCHazopDetail({id: id}); // 详情
            if(res.success){
                let setArr: any = [];
                let tableArr: any = [];
                let detailObj: any = {};
                if(res.data.l_FileId){
                    await getFileFun(res.data.l_FileId).then((item: any) => {
                        if(item.length !== 0){
                            item.map((val: any) => {
                                let itemObj: any = {};
                                itemObj['id'] = val.id;
                                itemObj['fileObjectName'] = val.fileObjectName;
                                itemObj['附件名称'] = val.fileOriginName;
                                itemObj['文件格式'] = val.fileSuffix;
                                itemObj['文件大小'] = val.fileSizeKb;
                                itemObj['文件路径'] = val.filePath;
                                tableArr.push(itemObj);
                            });
                        }
                    });
                }
                
                detailObj['风险分区'] = res.data.v_RiskPartitionName;
                detailObj['评价单位'] = res.data.v_EvaluationUnit;
                detailObj['评价日期'] = res.data.d_EvaluationDate  ? res.data.d_EvaluationDate.split(' ')[0] : '-';
                detailObj['评价单位资质'] = res.data.v_UnitQualification;
                detailObj['人员资质'] = res.data.v_PenpleQualification;
                detailObj['审核人'] = res.data.v_Auditor;
                detailObj['批准人'] = res.data.v_Approver;
                setArr = [{
                    formTitle: '基础信息',
                    type: 'form',
                    info: detailObj,
                },{
                    tableTitle: '文档数据',
                    type: 'table',
                    listData: tableArr,
                    minWidth: 160,
                    isShowBtn: true,
                }];
                detailInfo.value = setArr;
                MdetailDialog.value = true;
            }
        }
        /*** 详情 */
        const detailHandle = (id: number) => {
            getDetailFun(id);
        }
        /*** 详情关闭事件 */
        const cancelDetailClick = () => {
            MdetailDialog.value = false;
        }
        /*** ================================= 详情类数据操作 =================================  */
        
        /*** ================================= 查询类数据操作 =================================  */
        let searchObj:any = reactive({});
        const basicsInfo: any = ref([]);
        const searInfo: any = ref();

        /*** 获取需要查询的数据 */
        const searchHandel = (val: any) => {
            searInfo.value = val;
        }

        /*** 查询按钮 */
        const searchClick = () => {
            let newObj = Object.keys(searInfo.value);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = searInfo.value[i];
                });
            }
        };

        /*** 重置按钮 */
        const resetClick = () => {
            searInfo.value = {};
            let newObj = Object.keys(searchObj);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = ''
                });
            }
            initInfoFun();
        };

        let riskArr: any = [];
        // 获取数据
        const getFun = async () => {
            let ras: any = await SMSDCRiskPartitionList({}); // 风险分区
            if(ras.success && ras.data.length !== 0){
                ras.data.map((item: any) => {
                    item.label = item.v_Name;
                    item.value = item.id;
                });
                riskArr = ras.data;
            }
        }
        
        /*** 初始化数据 */
        const initInfoFun = () => {
            basicsInfo.value = [{
                    typeId: 'd_Public', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchValMin: 'd_PublicDateMin', // 查询字段 --- 必填
                    searchValMax: 'd_PublicDateMax', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '公告日期', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: '', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: '', // 事件名称 --- 选填
                },{
                    typeId: 'i_Principal', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'v_Principal', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '主要负责人', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: '', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: '', // 事件名称 --- 选填
                },{
                    typeId: 'i_Content', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'v_Content', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '描述', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: '', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: '', // 事件名称 --- 选填
                },{
                    typeId: 'd_Transfer', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchValMin: 'd_TransferTimeMin', // 查询字段 --- 必填
                    searchValMax: 'd_TransferTimeMax', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '传输(到显示屏)时间', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: '', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: '', // 事件名称 --- 选填
                }
            ]
        }
        
        onMounted(async () => {
            await getFun();
            initInfoFun(); 
        });
        /*** ================================= 查询类数据操作 =================================  */

        /*** ================================= 导出数据函数操作 ================================= */
        const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['公告时间'] = item.d_PublicDate ? item.d_PublicDate : '-';
                        tableObj['主要负责人'] = item.v_Principal ? item.v_Principal : '-';
                        tableObj['描述'] = item.v_Content ? item.v_Content : '-';
                        tableObj['传输(到显示屏)时间'] = item.d_TransferTime ? item.d_TransferTime : '-';
                        tableObj['传输(到显示屏)操作人'] = item.v_TransferOperatorName ? item.v_TransferOperatorName : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'承诺卡.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }
        /*** ================================= 导出数据函数操作 ================================= */

        return {
            ...getTableData(SMSDCRiskJudPubPage,{},searchObj),
            repairInfo,
            isUseDialog,
            nodeClick,
            cancelUseClick,
            controlUseClick,
            deleteHandle,
            syncHandel,

            // 导出Excel
            excelRef,
            handleExport,
            
            // 详情
            MdetailDialog,
            detailHandle,
            detailInfo,
            cancelDetailClick,

            // 查询事件
            basicsInfo,
            searchHandel,
            searchClick,
            resetClick,
        }
    },
} )
</script>
<style lang="scss"> @import '../style/public.scss'; </style>
<style scoped lang="scss">
    .search-s{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        width: 100%;
        .search-s-l{
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            width: 98%;
        }
    }
    #CommitmentCard {
        .box-f{
            :deep(.el-form-item__label){
                padding: 0;
            }
        }
        :deep(.el-card__body) {
            height: 100%;
        }
        :deep(.el-card){
            border: none !important;
        }
        .upload-demo{
            margin-left: 12px;
            margin-top: 2px;
        }
        .icon-e{
            :deep(.el-icon){
                margin-right: 0px!important;
            }
        }
    }
.clear-bg{
    background-color: transparent !important;
}
</style>
